<script setup lang="ts">
import { ref, computed } from 'vue';
import { Field, Button, showToast, Checkbox, CellGroup } from 'vant';

import  rq  from '@/utils/request';

import { useRouter } from 'vue-router';
const router = useRouter();

// 定义表单数据
const phone = ref('15244667237');
const code = ref('');
const agree = ref(false);

// 正则表达式校验
const isPhoneValid = computed(() => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone.value);
});

const isCodeValid = computed(() => {
  const codeRegex = /^\d{6}$/;
  return codeRegex.test(code.value);
});

// 是否可以点击登录按钮
const canLogin = computed(() => {
  return isPhoneValid.value && isCodeValid.value && agree.value;
});

// 模拟发送验证码
const sendCode = async () => {
  if (isPhoneValid.value) {
    const response = await rq('/code', 'get', { phone: phone.value });
    code.value = response.data.code;
    showToast('验证码已发送');
  } else {
    showToast('请输入正确的手机号');
  }
};

// 登录逻辑
const login = async () => {
  if (canLogin.value) {
    try {
      const response = await rq('/login', 'post', { phone: phone.value, code: code.value });
      if (response.code == 666) {
        showToast('登录成功');
        router.push('/user');
      } else {
        showToast('登录失败');
      }
    } catch (error) {
      showToast('登录失败:',error);
    }
  } else {
    showToast('请检查输入并同意协议');
  }
};

</script>

<template>
  <div class="login-container">
    <h2>登录</h2>
    <CellGroup>
      <Field
        v-model="phone"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请输入正确的手机号' }]"
        :error-message="!isPhoneValid && phone ? '请输入正确的手机号' : ''"
      />
      <Field
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '请输入正确的验证码' }]"
        :error-message="!isCodeValid && code ? '请输入正确的验证码' : ''"
      >
        <template #button>
          <Button size="small" type="primary" @click="sendCode" :disabled="!isPhoneValid">获取验证码</Button>
        </template>
      </Field>
    </CellGroup>
    <Checkbox v-model="agree" shape="square">
      我已阅读并同意<a href="#">用户协议</a>
    </Checkbox>
    <Button type="primary" block @click="login" :disabled="!canLogin">登录</Button>
  </div>
</template>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #f9f9f9;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}

.van-cell-group {
  margin-bottom: 15px;
}

.van-field__label {
  width: 70px;
}

.van-button--small {
  margin-left: 10px;
}

.van-checkbox {
  margin-bottom: 15px;
}

.van-checkbox__label a {
  color: #007bff;
  text-decoration: none;
}

.van-button--block {
  width: 100%;
  padding: 10px;
  border-radius: 4px;
  font-size: 16px;
}
</style>